package cn.oracle.eshop.auth.visitor;

import cn.oracle.eshop.auth.composite.PriorityNode;
import cn.oracle.eshop.auth.dao.AccountPriorityRelationshipDAO;
import cn.oracle.eshop.auth.dao.PriorityDAO;
import cn.oracle.eshop.auth.dao.RolePriorityRelationshipDAO;
import cn.oracle.eshop.auth.domain.PriorityDo;
import cn.oracle.eshop.auth.mapper.AccountPriorityRelationshipMapper;

import java.util.List;

/** 权限树节点的关联检查访问者
 * @author wyh
 * @ClassName PriorityNodeRelateCheckVisitor
 * @date 2022/1/22 /17:32
 */

public class PriorityNodeRelateCheckVisitor implements PriorityNodeVisitor{
   /***
    * 关联检查结果
    * @author wyh
    * @date 2022/1/22
    * @param null
    * @return
   */
    private Boolean relateCheckResult=false;
   /**权限管理模块的DAO组件*/
    private PriorityDAO priorityDAO;
    /**角色和权限关系管理模块的DAO组件*/
    private RolePriorityRelationshipDAO rolePriorityRelationshipDAO;
    /**账号和权限关系管理模块的DAO组件*/
    private AccountPriorityRelationshipDAO accountPriorityRelationshipDAO;
/***
 * 构造函数
 * @author wyh
 * @date 2022/1/22
 * @param priorityDAO 权限管理模块的DAO组件
 * @param rolePriorityRelationshipDAO 角色和权限关系管理模块的DAO组件
 * @param   accountPriorityRelationshipDAO    账号和权限关系管理模块的DAO组件
 * @return
*/
    public PriorityNodeRelateCheckVisitor(PriorityDAO priorityDAO,
                                          RolePriorityRelationshipDAO rolePriorityRelationshipDAO,
                                          AccountPriorityRelationshipDAO accountPriorityRelationshipDAO) {
      this.priorityDAO=priorityDAO;
      this.rolePriorityRelationshipDAO=rolePriorityRelationshipDAO;
      this.accountPriorityRelationshipDAO=accountPriorityRelationshipDAO;
    }

    public Boolean getRelateCheckResult() {
        return relateCheckResult;
    }

    /**访问权限树节点*/
    @Override
    public void visit(PriorityNode node) {
        List<PriorityDo> priorityDos=priorityDAO.listChildPriorities(node.getId());
        if(priorityDos !=null && priorityDos.size()>0){
            for (PriorityDo priorityDo : priorityDos) {
                //把do的数据克隆到Node里面,拿到所有的子节点
                PriorityNode priorityNode=priorityDo.clone(PriorityNode.class);
                priorityNode.accept(this);
            }
        }
if(relateCheck(node)){
    relateCheckResult=true;
}
    }
    /**检查权限是否被任何一个角色或者是账号关联了
     * @param node 权限树节点
     * @return 是否被任何一个角色或者是账号关联了，如果有关联则为true,如果没有则为false
     * */
    private Boolean relateCheck(PriorityNode node){
        Long roleRelatedCount = rolePriorityRelationshipDAO.getCountByPriorityId(node.getId());
        if (roleRelatedCount != null && roleRelatedCount > 0) {
            return true;
        }
        Long accountRealtedCount = accountPriorityRelationshipDAO.getCountByPriorityId(node.getId());
        if (accountRealtedCount != null && accountRealtedCount > 0) {
            return true;
        }
        return false;
    }
}
